﻿using JZ_UDI.DataAccess;
using JZ_UDI.DataAccess.DataEntity;
using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JZ_UDI
{
    public partial class frmChangPwd : Form
    {
        public frmChangPwd()
        {
            InitializeComponent();
        }

        private void frmChangPwd_Load(object sender, EventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!CommonHelper.MD5Helper.MD5Encrypt32(txtOldPassword.Text.Trim()).Equals(Global.UserInfo.Password) || string.IsNullOrEmpty(txtOldPassword.Text.Trim()))
            {
                MessageBox.Show("旧密码不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrEmpty(txtNewPassword.Text.Trim()))
            {
                MessageBox.Show("请输入新密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrEmpty(txtCheckPassword.Text.Trim()))
            {
                MessageBox.Show("请输入确认密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!txtNewPassword.Text.Trim().Equals(txtCheckPassword.Text.Trim()))
            {
                MessageBox.Show("新密码不相同", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string newPwd = CommonHelper.MD5Helper.MD5Encrypt32(txtCheckPassword.Text.Trim());
            Global.UserInfo.Password = newPwd;

            using (var context = new EFDbContext())
            {

                User p = context.Users.ToList().Find(o => o.UserName == Global.UserInfo.UserName);
                if (p != null)
                {
                    p.Password = newPwd;
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        Global.SaveLogger(LogLevel.Info, Global.logger.Name, "更新密码成功" );
                        MessageBox.Show("更新密码成功,请重新登陆！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                        Application.Exit(); 
                    }
                }
            }

        }
    }
}
